<script setup>
import {ref, reactive, onMounted, watch, defineExpose} from 'vue'
import {ElTable, ElTableColumn, ElPagination, ElInput, ElButton,ElMessage} from 'element-plus'
import {getConsumablesStoreList,} from "@/api/ConsumablesStore.js"
import {getConsumablesCategoryTree,} from "@/api/ConsumablesCategory.js"
import {getConsumablesList} from "@/api/ConsumablesList.js"
import {Search} from '@element-plus/icons-vue'
// 耗材表格数据
const tableData = ref([])
// 耗材分类列表数据
const CategoryListData = ref([])
// 仓库列表数据
const StoreListData = ref([])

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})
//接收父组件传值
const props = defineProps({
  wid: {
    type: [String, Number],
    default: ''
  }
})

// 搜索条件
const searchParams = reactive({
  name: '',
  categoryId: '',
  warehouseId: ''
})

watch(
    () => props.wid,
    (newUser, oldUser) => {
      searchParams.warehouseId = newUser
      loadData()
      console.log('用户对象深度变化:', newUser)
    },
    {deep: true} // 深度监听所有嵌套属性
)


//加载耗材分类数据
const getCategoryListData = async () => {
  try {
    getConsumablesCategoryTree().then(res => {
      console.log("耗材分类：", res)
      CategoryListData.value = res.data
    })

  } catch (error) {
    console.error('数据加载失败')
  }
}
// 加载数据
const loadData = async () => {

  let data = {
    ...searchParams,
    ...pagination
  }
  try {
    getConsumablesList(data).then(res => {
      console.log("耗材列表：", res)
      //tableData.value = res.data[0].mlist
      if (res.data[0].mlist != null) {
        for (let i = 0; i < res.data[0].mlist.length; i++) {
          res.data[0].mlist[i].materialNum = 1
        }
      }
      tableData.value = res.data[0].mlist
      pagination.total = res.data[0].total
    })

  } catch (error) {
    console.error('数据加载失败')
  }
}

// 搜索重置
const resetSearch = () => {
  searchParams.name = ''
  searchParams.categoryId = ''
  loadData()
}


//分页
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pagination.pageSize = val
  loadData()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  pagination.page = val
  loadData()
}

const emit = defineEmits(['consumableSelect'])
defineExpose({
  resetSearch
})
// 选择的资源列表
const multipleSelection = ref([])
// 当选择资源时
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  //获取选中的资源列表 传递给父组件
//   borrowForm.value.assets = multipleSelection.value
  console.log(val, 99999)
  emit('consumableSelect', val)
}
//数量的change事件：监听数量变化
const changeNum = (row) => {
  //console.log(555,row)
  if (row.materialNum==null ) {
    row.materialNum = 1
    return ElMessage.error('耗材数量不能为空！')
  }
  if (row.materialNum==0 ) {
    row.materialNum = 1
    return ElMessage.error('耗材数量不能为0！')
  }
  if (row.materialNum>row.quantity ) {
    row.materialNum = row.quantity
    return ElMessage.error('耗材数量不能大于当前库存！')
  }
  for (let i = 0; i < multipleSelection.value.length; i++) {
    if (multipleSelection.value[i].materialId == row.materialId) {
      multipleSelection.value[i] = row
      emit('consumableSelect', multipleSelection.value)
    }
  }
}

// 生命周期钩子
onMounted(() => {
  loadData()
  getCategoryListData()
  getConsumablesStoreList().then(res => {
    StoreListData.value = res.data
  })
})

</script>

<template>
  <div class="">
    <el-form :inline="true" :model="searchParams" class="demo-form-inline" style="margin-top: 10px;">
      <el-form-item label="耗材名称">
        <el-input
            v-model="searchParams.name"
            placeholder="请输入耗材名称"
            clearable
            style="width: 230px; "
            :prefix-icon="Search"
        />
      </el-form-item>
      <el-form-item label="类别">
        <el-tree-select
            v-model="searchParams.categoryId" placeholder="请选择类别"
            :data="CategoryListData"
            node-key="id"
            :props="{label:'name',children:'children'}"
            check-strictly
            :render-after-expand="false"
            style="width: 230px; "
            clearable
        ></el-tree-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadData">
          <el-icon>
            <el-icon-search/>
          </el-icon>
          搜索
        </el-button>
        <el-button @click="resetSearch">
          <el-icon>
            <el-icon-refresh/>
          </el-icon>
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border size="small" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" fixed/>
      <el-table-column prop="code" label="耗材编码"/>
      <el-table-column prop="name" label="耗材名称"/>
      <el-table-column prop="specification" label="规格型号"/>
      <el-table-column prop="unit" label="单位" width="80"/>
      <el-table-column prop="categoryName" label="耗材类别"/>
      <el-table-column prop="quantity" label="当前库存" width="80"/>
      <el-table-column prop="warehouseName" label="仓库位置"/>
      <el-table-column prop="materialNum" label="数量" width="150">
        <template #default="scope">
          <el-input-number v-model="scope.row.materialNum" :min="0" :max="parseInt(scope.row.quantity)" size="small"
                           @change="changeNum(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column prop="materialDesc" label="耗材备注">
        <template #default="scope">
          <el-input v-model="scope.row.materialDesc" clearable></el-input>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        layout="slot, prev, pager, next"
        style="margin-top: 20px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    >
      <el-text key="1">总条数：{{ pagination.total }}</el-text>
    </el-pagination>


  </div>
</template>

<style scoped>
.el-pagination {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  margin-top: 20px; /* 根据需要调整间距 */
}

/*.page-container {
  box-sizing: border-box;
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}*/
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}
</style>